package com.example.demo.controller;

import com.example.demo.dto.AccessTokenDTO;
import com.example.demo.dto.GitHubUser;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.provider.GitHubProvider;
import com.example.demo.server.AuthorizeUserService;
import com.example.demo.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/***
 *
 * github 账号自动登陆
 * https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
 */
//1b66d0b190ce1ebb4562

//    ff28a0da945297e66c25b051db526cb98cc8cbb4

//    7718b1e68abe0e48c81b2fc7a992a559877dbf9f

@Controller
public class AuthorizeController {

    @Autowired
    private GitHubProvider gitHubProvider;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthorizeUserService userService;// 这里和视频中的命名有区别

    @Value("${gitee.oauth.client_id}")
    private String clientId;
    @Value("${gitee.oauth.client_secret}")
    private String clientSecret;
    @Value("${gitee.oauth.redirect_uri}")
    private String redirectUri;

    @Transactional
    @GetMapping("/callback")
    public String callBack(@RequestParam(value = "code", required = false) String code,
                           @RequestParam(value = "state", required = false) String state,
                           HttpServletRequest request,
                           HttpServletResponse response) {

        System.out.println("code===" + code);
        System.out.println("state====" + state);
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);

        System.out.println("!!!!!!!!!!!!!!!!!!!!!accessToken"+accessToken);
        GitHubUser gitHubUser = gitHubProvider.getUser(accessToken);
        if (!ObjectUtils.isEmpty(gitHubUser) && gitHubUser != null) {
            // TODO: 2020/4/14  登录成功将信息保存如session

            User user = new User();
            String token = UUID.randomUUID().toString();
            System.out.println("token==" + token);
            System.out.println("Nam===" + gitHubUser.getName());
            System.out.println("AccountId==" + String.valueOf(gitHubUser.getId()));
            System.out.println("GmtCreate==" + System.currentTimeMillis());
            System.out.println("GmtModified==" + user.getGmtCreate());
            System.out.println("AvatarUrl==" + gitHubUser.getAvatarUrl());
            user.setToken(token);
            if (null == gitHubUser.getName() || gitHubUser.getName().equals("")) {
                user.setName(gitHubUser.getName());
            } else {
                user.setName("p");
            }
            if (null == gitHubUser.getId() || gitHubUser.getId().equals("")) {
                user.setAccountId("1");
            } else {
                user.setName("1");
            }

            user.setGmtCreate(System.currentTimeMillis());
            if (null == user.getGmtCreate() || user.getGmtCreate().equals("")) {
                user.setGmtModified(user.getGmtCreate());
            } else {
                user.setName("p");
            }
            user.setAvatarUrl(gitHubUser.getAvatarUrl());//  设值头像图片


            userMapper.insert(user);
//             创建这个方法
            userService.createOrUpdata(user);
            Cookie cookie = new Cookie("token", token);

            response.addCookie(new Cookie("token", token));//添加一个cook
            cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
            System.out.println("成功登陆");
            return "redirect:/";//  此处使用mvc的重定向
        } else {
            // TODO: 2020/4/14 显示失败原因
            System.out.println("失败原因");
            return "redirect:/";
        }
    }

    /***
     * 添加一个退出 登陆功能
     * 技巧 将cook  和sesstion  设置为空后传入存储
     *
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {

        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}


//#github
//        172.17.0.1 github.com git
//        13.250.177.223 github.com